// backend/services/imageService.js
const axios = require('axios');
const fs = require('fs');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const config = require('../config');
const logger = require('./logger');

function getImageUrl(prompt) {
  const encodedPrompt = encodeURIComponent(prompt);
  return config.image.apiUrl.replace('{prompt}', encodedPrompt);
}

/**
 * 【核心修改】下载图片并保存到本地，增加了重试和超时机制
 * @param {string} imageUrl - 要下载的图片的外部URL
 * @param {number} retries - 允许的重试次数
 * @returns {Promise<string|null>} - 成功则返回本地路径，失败则返回null
 */
async function downloadAndSaveImage(imageUrl, retries = 2) {
  for (let i = 0; i <= retries; i++) {
    try {
      logger.info(`Attempt ${i + 1}/${retries + 1}: Downloading image from ${imageUrl}`);
      const response = await axios({
        url: imageUrl,
        method: 'GET',
        responseType: 'stream',
        timeout: 30000, // 设置30秒超时
      });

      const imageName = `${uuidv4()}.jpg`;
      const localFolderPath = path.join(__dirname, '..', 'public', 'images');
      const localFilePath = path.join(localFolderPath, imageName);

      if (!fs.existsSync(localFolderPath)) {
          fs.mkdirSync(localFolderPath, { recursive: true });
      }
      
      const writer = fs.createWriteStream(localFilePath);
      response.data.pipe(writer);

      await new Promise((resolve, reject) => {
        writer.on('finish', resolve);
        writer.on('error', reject); // 文件写入错误
      });

      logger.info(`Image successfully downloaded to: ${localFilePath}`);
      return `/images/${imageName}`; // 成功，返回路径并退出循环

    } catch (error) {
      logger.warn(`Attempt ${i + 1} failed for ${imageUrl}. Error: ${error.code || error.message}`);
      if (i === retries) {
        // 如果这是最后一次重试，则记录严重错误并返回null
        logger.error(`Failed to download image after ${retries + 1} attempts: ${imageUrl}`, error);
        return null; // 所有重试都失败了
      }
      // 等待一段时间再重试 (例如2秒)
      await new Promise(resolve => setTimeout(resolve, 2000));
    }
  }
}

module.exports = { getImageUrl, downloadAndSaveImage };
